package com.example.user.adapter.in.web.controller;

import com.example.user.adapter.in.web.dto.*;
import com.example.user.adapter.in.web.service.TokenBlacklistService;
import com.example.user.service.application.command.CreateUserCommand;
import com.example.user.service.application.command.UpdateUserCommand;
import com.example.user.service.application.command.UserLoginCommand;
import com.example.user.service.application.port.in.*;
import com.example.user.service.domain.User;
import com.example.user.service.domain.port.GetUserByNamePort;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RequestMapping("/users")
@RestController
@RequiredArgsConstructor
public class UserController {

    private final GetUserListUseCase getUserListUseCase;
    private final CreateUserUseCase createUserUseCase;
    private final DeleteUserUseCase deleteUserUseCase;
    private final UpdateUserUseCase updateUserUseCase;
    private final GetUserByIdUseCase getUserByIdUseCase;
    private final UserLoginUseCase userLoginUseCase;
    private final GetUserByNamePort getUserByNamePort;
    private final TokenBlacklistService tokenBlacklistService;


    @PostMapping("login")
    public String login(@RequestBody UserLoginRequestDTO userLoginRequestDTO){
        log.info("UserLoginRequestDTO:{}",userLoginRequestDTO);
        UserLoginCommand command=UserLoginCommand.builder()
                .name(userLoginRequestDTO.getName())
                .password(userLoginRequestDTO.getPassword())
                .build();
        return userLoginUseCase.login(command);
    }



    @GetMapping("")
    public List<User> getUsers() {
        log.info("getUsers");
        return getUserListUseCase.getUsers();
    }

    /**
     * 创建新用户
     * 功能：接收用户注册信息，验证密码一致性，创建新用户账户
     * @author dongxuanfeng
     * @param createUserRequestDTO
     * @return User - 成功创建的新用户
     * @throws IllegalArgumentException 当密码与确认密码不匹配时抛出此异常
     */
    @PostMapping()
    public User createUser(@RequestBody CreateUserRequestDTO createUserRequestDTO){

        if (!createUserRequestDTO.isPasswordValid()) {
            throw new IllegalArgumentException("密码和确认密码不匹配");
        }
        CreateUserCommand command=CreateUserCommand.builder()
                .name(createUserRequestDTO.name())
                .age(createUserRequestDTO.age())
                .email(createUserRequestDTO.email())
                .password(createUserRequestDTO.password())
                .isSuper(createUserRequestDTO.isSuper())
                .build();
        User existingUser = User.getUserByName(createUserRequestDTO.name(),getUserByNamePort);
        try{
            if (existingUser != null) {
                log.warn("注册失败: 用户名已存在 - {}", createUserRequestDTO.name());
                return Result.error("用户名已存在，请选择其他用户名");
            }
            User user = createUserUseCase.createUser(command);
            if(user != null){
                return Result.success("注册成功",user);
            }else {
                return Result.error("注册失败，请稍后重试");
            }
        }catch (Exception e){
            log.error("用户注册失败: 数据库插入失败 - {}", createUserRequestDTO.name());
            log.info(e.getMessage());
            return Result.error("注册失败，请稍后重试");
        }
    }


    @DeleteMapping("{id}")
    public String deleteUser(@PathVariable("id") Long id){
        deleteUserUseCase.deleteUser(id);
        return "success";
    }


    @PutMapping("")
    public User updateUser(@RequestBody UpdateUserRequestDTO updateUserRequestDTO){

        UpdateUserCommand command=UpdateUserCommand.builder()
                .id(updateUserRequestDTO.id())
                .name(updateUserRequestDTO.name())
                .age(updateUserRequestDTO.age())
                .email(updateUserRequestDTO.email())
                .is_super(updateUserRequestDTO.is_super())
                .build();
        User user = updateUserUseCase.updateUser(command);
        return user;
    }



    @GetMapping("{id}")
    public UserResponseDTO getUserById(@PathVariable("id") Long id){
        User user = getUserByIdUseCase.getUserById(id);
        UserResponseDTO userResponseDTO = new UserResponseDTO(
                user.getId().id(),
                user.getName().username(),
                user.getAge().age(),
                user.getEmail().email(),
                user.getIsSuper().value());
        return userResponseDTO;
    }

}
